package com.liliudong.rommath.handler;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.SaTokenException;
import cn.hutool.core.text.CharPool;
import cn.hutool.http.HttpStatus;
import com.liliudong.rommath.common.R;
import com.liliudong.rommath.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.stream.Collectors;


/**
 * 全局异常捕获
 *
 * @author ldli5
 * @classname GlobleExceptionHandler
 * @date 2024/6/18-15:05
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public R<?> exHandler(Exception e) {
        log.error(e.getMessage(), e);
        return R.error("系统异常, 请联系管理员");
    }

    @ExceptionHandler(NoResourceFoundException.class)
    public R<?> exHandler(NoResourceFoundException e) {
        log.error(e.getMessage(), e);
        return R.error(e.getMessage());
    }

    @ExceptionHandler(BizException.class)
    public R<?> exHandler(BizException e) {
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public R<?> exHandler(BindException e) {
        String msg = e.getFieldErrors().stream()
                .map(fieldError -> {
                    String field = fieldError.getField();
                    String defaultMessage = fieldError.getDefaultMessage();
                    return field + CharPool.COLON + defaultMessage;
                }).collect(Collectors.joining(","));
        log.error("参数校验异常:{}", msg);
        return R.error(msg);
    }

    @ExceptionHandler(SaTokenException.class)
    public R<?> exHandler(SaTokenException e) {
        log.error(e.getMessage(), e);
        return R.error("认证异常", HttpStatus.HTTP_UNAUTHORIZED);
    }

    @ExceptionHandler(NotPermissionException.class)
    public R<?> exHandler(NotPermissionException e) {
        log.error(e.getMessage(), e);
        return R.error("权限不足", HttpStatus.HTTP_FORBIDDEN);
    }

}
